// Copyright 2013 The Go Circuit Project
// Use of this source code is governed by the license for
// The Go Circuit Project, found in the LICENSE file.
//
// Authors:
//   2013 Petar Maymounkov <p@gocircuit.org>

package ripple

import (
	"bufio"
	"io"

	"circuit/kit/rh"
	"circuit/kit/rh/ns"
)

const maxCommandLen = 1e4 // 10K

// NewEndpoint creates a line-oriented endpoint, where naive line-splitting is
// done and only the first line is passed to eval.
func NewEndpoint(eval func(string)) rh.FID {
	return ns.RegulateFork(func() ns.UnregulatedFID {
		fid, r := ns.NewPipeWriterFID("")
		go func() {
			scanner := bufio.NewScanner(io.LimitReader(r, maxCommandLen))
			for scanner.Scan() {
				eval(scanner.Text())
				break
			}
			r.Close()
		}()
		return fid
	})
}

// NewRawEndpoint creates a "raw" endpoint, in that no parsing is done - the
// length-limited io.Reader is passed directly to eval.
func NewRawEndpoint(eval func(io.Reader)) rh.FID {
	return ns.RegulateFork(func() ns.UnregulatedFID {
		fid, r := ns.NewPipeWriterFID("")
		go func() {
			defer r.Close()
			eval(io.LimitReader(r, maxCommandLen))
		}()
		return fid
	})
}
